#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define P(S) (sem_wait(S))
#define V(S) (sem_post(S))
#define MYMAX 4

typedef sem_t semaphore;
semaphore full,empty;
int B=0;

void *producer(){
	int i;
	for (i=1;i<=MYMAX;i++){
		P(&empty);
		B=i;
		printf("生产 %d\n",B);
		V(&full);
	}
}

void *consumer(){
	int i;
	for (i=1;i<=MYMAX;i++){
		P(&full);
		sleep(1);	//模拟速度不一致	
		printf("消费 %d\n",B);
		B=0; 
		V(&empty);
	}
}

int main()
{
	pthread_t tidp,tidc;
	sem_init(&full,0,0); //full=0
	sem_init(&empty,0,1); //empty=1
	pthread_create(&tidp,NULL,producer,NULL);
	pthread_create(&tidc,NULL,consumer,NULL);
	printf("main thread start...\n");
	pthread_join(tidp,NULL);
	pthread_join(tidc,NULL);
	return 0;
}